package t25524;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    Connection connection = SqlConnection.getConnection();
    public UserDao() throws ClassNotFoundException, SQLException, SQLException {}
    public  int  addUser(String username, String password) throws ClassNotFoundException, SQLException {
        Connection connection = SqlConnection.getConnection();
        String sql = "insert into users(username,password) values(?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        return preparedStatement.executeUpdate();
    }
    public Users login(String username, String password) throws ClassNotFoundException, SQLException {
        Users  users = new Users();
        Connection connection = SqlConnection.getConnection();
        String sql = "select * from users where username = ? and password = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            users.setId(resultSet.getInt("id"));
            users.setUsername(resultSet.getString("username"));
            users.setPassword(resultSet.getString("password"));
        }
        return users;
    }
    public int deleteUsers( int id) throws  ClassNotFoundException,SQLException {
        Connection connection = SqlConnection.getConnection();
        String sql = "DELETE FROM users WHERE id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, id);
        return preparedStatement.executeUpdate();
    }
    public int updateUsers(int id, String username, String password) throws ClassNotFoundException, SQLException {
        Connection connection = SqlConnection.getConnection();
        String sql = "UPDATE users SET username = ?, password = ? WHERE id = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        preparedStatement.setInt(3, id);
        return preparedStatement.executeUpdate();
    }
}
